package com.example.main
import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.KeyEvent
import android.view.View
import android.webkit.JavascriptInterface
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.common.base.BaseActivity
import com.example.common.dialog.AppUpdateDialog
import com.example.main.databinding.ActivityMainBinding
import com.example.path.RouterPath
import com.tencent.mmkv.MMKV
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebViewClient
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = RouterPath.PATH_MAIN)
class MainActivity : BaseActivity<ActivityMainBinding>(){

    private var mBackClickCount =0
    private var hasUnGranted =false
    private lateinit var mAppUpdateDialog: AppUpdateDialog
    //应用需要的权限
    private var needUserPermissions = arrayListOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.RECORD_AUDIO,
    )
    //未授权的权限
    private var unGrantedPermission = mutableListOf<String>()
    override fun getLayoutId(): Int=R.layout.activity_main

    override fun initViews() {
        //更新弹窗
        appUpDataDialog()
        //获取登录状态的页面
        x5WebViewInit()

    }
    private fun requestPermission() :Boolean{
        //Android 6.0以上需要动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //检查用户是否同意了权限
            unGrantedPermission.clear()
            needUserPermissions.forEach {
               var state= checkSelfPermission(it)
                if (state==PackageManager.PERMISSION_DENIED){//用户拒绝权限
                    unGrantedPermission.add(it)
                }
            }
            //发起用户权限
            if (unGrantedPermission.size>0){
                requestPermissions(unGrantedPermission.toTypedArray(),100)
                    return false
            }
        }
        return true
    }

    private fun x5WebViewInit(){
        //获取登录状态的页面
        var mainUrl=  MMKV.defaultMMKV().decodeString("main_url","")
        mDataBinding.web.webChromeClient= WebChromeClient()
        mDataBinding.web.webViewClient=WebViewClient()
        mDataBinding.web.loadUrl(mainUrl)
        //设置X5WebView
        mDataBinding.web.view.overScrollMode=View.OVER_SCROLL_NEVER
        mDataBinding.web.addJavascriptInterface(WebViewJsInterface(),"androidinfo")//别名必须和前端一致
        //延迟权限设置展示
        mDataBinding.web.postDelayed({
            requestPermission()
        },1000)
    }

    private fun appUpDataDialog(){
        mAppUpdateDialog= AppUpdateDialog(this)
        //模拟App更新弹窗
        var hasNewApp =MMKV.defaultMMKV().decodeBool("hasNewApp",true)
        if (!hasNewApp){
            MMKV.defaultMMKV().encode("hasNewApp",false)
            mDataBinding.web.postDelayed({
                mAppUpdateDialog.show()
            },2000)
        }
    }

    /**
     * 打开应用详情页面
     * */
    private fun openAppDetailPage(){
        var intent=Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data= Uri.fromParts("package",packageName,null)
        startActivity(intent)
    }
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //再次检查用户是否全部同意
        if (requestCode==100 && Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            unGrantedPermission.forEach {
                if(checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted =true
                }
            }
        }
        //给出权限提示
        if (hasUnGranted){
            var builder =AlertDialog.Builder(this@MainActivity)
            builder.setTitle("权限授权")
            builder.setMessage("没有授权,请到设置中授权")
            builder.setPositiveButton("去设置"){dialog,_ ->
                dialog.dismiss()
                openAppDetailPage()
                hasUnGranted=false
            }
            builder.setNegativeButton("取消"){dialog,_ ->
                dialog.dismiss()
                hasUnGranted=false
            }
            var alertDialog=builder.create()
            alertDialog.show()

        }

    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        //处理返回按键还是回退上一页
        if (keyCode== KeyEvent.KEYCODE_BACK && mDataBinding.web.canGoBack()){
            mDataBinding.web.goBack()
            return true
        }
        //实现一个双击退出
          if (keyCode==KeyEvent.KEYCODE_BACK){
              mBackClickCount+=1
          }
        //显示用户点击返回键退出
        if (mBackClickCount==1){
            ToastUtils.showLong("再按一次退出")
            return true
        }

        return super.onKeyDown(keyCode, event)
    }

    override fun onResume() {
        super.onResume()
        mDataBinding.web.onResume()
    }

    override fun onPause() {
        super.onPause()
        mDataBinding.web.onPause()
    }
    override fun onDestroy() {
        super.onDestroy()
        //清理WebView
        mDataBinding.web.clearCache(true)
        mDataBinding.web.clearHistory()
        mDataBinding.web.removeAllViews()
        mDataBinding.web.destroy()

    }
    /**
     * 记录业务模块
     * */
    private fun jumpModuleActivity(moduleType: String){
        //只有所有权限都授权了才能跳转
        var hasAllPemission = requestPermission()
        if (!hasAllPemission)return
        when(moduleType){
            //物业管理
            "1","2","3","4","5","6" -> ARouter.getInstance().build(RouterPath.PATH_PROPERTY).withString("moduleType", moduleType).navigation()
            //园区文化
            "7","8","9","10" -> ARouter.getInstance().build(RouterPath.PATH_CULTURE).withString("moduleType", moduleType).navigation()
            //考勤
            "11", "12"-> ARouter.getInstance().build(RouterPath.PATH_ATTENDANCE).withString("moduleType", moduleType).navigation()
            //我的审核
            "13","14","15" -> ARouter.getInstance().build(RouterPath.PATH_AUDIT).withString("moduleType", moduleType).navigation()
            else -> showToastMessage("敬请期待！")
        }

    }

    /**
     * Js调用安卓方法
     * */
    inner class WebViewJsInterface{
        @JavascriptInterface
        fun androidparking(id: String){
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidapply(id: String){
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidvisit(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidpatrol(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidnews(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidnoticelist(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidrepair(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidaddrepair(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidaddculture(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidaddnotice(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidculture(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidnotice(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidsign(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidattendance(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidproperty(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidcheckculture(id: String) {
            jumpModuleActivity(id)
        }

        @JavascriptInterface
        fun androidpeople(id: String) {
            jumpModuleActivity(id)
        }

    }


}